import hashlib
import time

import requests


class CommonRequest(object):
    """
    公共请求类
    """
    def __init__(self):
        # 在平台“基本资料-安全设置”处可查看SecretId
        self.__secretId = "SecretId"
        # 在平台“基本资料-安全设置”处可查看SecretKey
        self.__secretKey = "SecretKey"
        # 接口地址（固定）
        self.__url = "https://xapi.xunai-tech.com"

    def create_headers(self):
        """
        创建请求头，生成校验参数
        :return:
        """
        # 请求端口时间,时间格式为毫秒级时间戳，如: 1199116800000.过期时间为一个小时,若当前参数与实际时间超出一个小时,会引起签名过期错误.
        timestamp = str(int(round(time.time() * 1000)))
        param_join = self.__secretId + timestamp + self.__secretKey
        headers = {
            "Accept": "application/json;",
            "Content-Type": "application/json;charset=utf-8;",
            "secretId": self.__secretId,
            "timestamp": timestamp,
            "sign": hashlib.md5(param_join.encode(encoding='UTF-8')).hexdigest()
        }
        return headers

    def post(self, path, body):
        print(self.__url + path, body)
        return requests.post(self.__url + path, json=body, headers=self.create_headers())

    def get(self, path):
        print(self.__url + path)
        return requests.get(self.__url + path, headers=self.create_headers())
